package com.jvm.classfile.model;

import com.jvm.Utils;
import com.jvm.interpreter.Instruction;
import lombok.Data;

import java.util.Map;

/**
 * @program: diy_simple_jvm
 * @description:
 * @author: CaoYong
 * @create: 2021-07-08 19:03
 **/
@Data
public class Method {

    public Class clazz;
    int accessFlags;
    String name;
    String descriptor;
    Code code;


    // 指令缓存
    Map<Integer, Instruction> instructions;

    public Method(int accessFlags, String name, String descriptor, Code code) {
        this.accessFlags = accessFlags;
        this.name = name;
        this.descriptor = descriptor;
        this.code = code;
    }

    public Map<Integer, Instruction> getInstructions() {
//        return this.code.getInstructions(clazz.classFile.getConstantPool());

        if (this.instructions != null) {
            return this.instructions;
        }

        final Map<Integer, Instruction> instructions = this.code.getInstructions(clazz.classFile.constantPool);
        this.instructions = instructions;
        return instructions;
    }

    public int getMaxLocals() {
        return this.code.maxLocals;
    }

    public int getMaxStack() {
        return this.code.maxStack;
    }

    public int getArgSlotSize() {

        final int size = Utils.getArgSlotSize(this.descriptor);
        if (Utils.isStatic(this.accessFlags)) {
            return size;
        }
        // 如果是非静态方法 slot的size加1
        return size + 1;
    }

}
